""" 

    Votes.py used in RepresentedBy Facebook application
    http://apps.facebook.com/representedby/
    
    This page is a webservice which takes a list of Ids and returns a list of the 10 most recent
    votes and how each legislator voted as a JSON object
    
    Accepts two parameters:
        ids (required) - comma delimited list of Bioguide Ids
        offset (optional) - used for paging to get records 11-20, 21-30, etc.
"""

__author__ = "Will Turnage (will @t wubbahed d0t com)"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2009 wubbahed.com"
__license__ = "GPLv3"


import wsgiref.handlers
import const
import facebook

from django.utils import simplejson
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
        
from utils import UserLikes, fbUtil, SunlightUtil, memcacheUtil, textUtil

class MainHandler(webapp.RequestHandler):

    def get(self):
        self.post()
        
    def post(self):
           
        self.response.headers["Content-Type"] = "application/json; charset=utf-8"
        jsonOutput = {"result":"ok", "message":"", "legislators":{}, "votes":[]}
        
        theIds = self.request.get('ids', default_value=None)
            
        if theIds is not None:
            
            newsCount = 6
            newsOffset = int(self.request.get('offset', default_value=0))
            memcache = memcacheUtil() 
            legislatorIds = theIds.split(",")
            votes = {}
            
            sunlight = SunlightUtil(const.SUNLIGHT_API_KEY)
            
            for legislatorId in legislatorIds:
                legislator = sunlight.apicall("legislators.get", {"bioguide_id": legislatorId})
                if legislator is not None:
                                 
                    legislator["legislator"]["friendly_name"] = const.FRIENDLY_NAME[legislatorId]
                    jsonOutput["legislators"][legislator["legislator"]["bioguide_id"]] = legislator["legislator"]
                    
                    legislator_votes = memcache.getJSONFromCache(const.NYTIMES_BASE_URL + "/members/" + str(legislatorId) + "/votes.json?api-key=" + const.NYTIMES_API_KEY, "results")
                    if legislator_votes is not None:
                        for vote in legislator_votes[0]["votes"]:
                            key = vote["date"] + "-" + vote["time"] + "-" + vote["member_id"] + "-" + vote["roll_call"]
                            votes[key.encode("ascii")] = vote
                
            keys = votes.keys()
            keys.sort(reverse=True)
            if keys is not None:

                billNames = memcache.get("representedby_billnames")
                if billNames is None:
                    billNames = {}
                               
                if len(keys) < (newsCount+newsOffset):
                    newsCount = len(keys) - newsOffset
                
                textutil = textUtil()
                for voteIndex in range(newsCount):
                    if (voteIndex + newsOffset) < len(keys):
                        billName = " "
                        if billNames.has_key(keys[voteIndex + newsOffset]):
                            billName = billNames[keys[voteIndex + newsOffset]]
                        else:
                            billNameResult = memcache.getJSONFromCache(const.NYTIMES_BASE_URL + "/" + str(votes[keys[voteIndex + newsOffset]]["congress"]) + "/" + str.lower(str(votes[keys[voteIndex + newsOffset]]["chamber"])) + "/sessions/" + str(votes[keys[voteIndex + newsOffset]]["session"]) + "/votes/" + str(votes[keys[voteIndex + newsOffset]]["roll_call"]) + ".json?api-key=" + const.NYTIMES_API_KEY, "results")
                            if billNameResult is not None:
                                if billNameResult["votes"]["vote"]["description"] is not None:
                                    tempDict =  {"result": str.lower(str(billNameResult["votes"]["vote"]["result"]))}
                                    tempDict["link"] = "http://www.opencongress.org/bill/" + const.CURRENT_CONGRESS + "-" + str.lower(str(billNameResult["votes"]["vote"]["bill_number"])[0]) + billNameResult["votes"]["vote"]["roll_call"] + "/show"     
                                    if billNameResult["votes"]["vote"]["description"] == "":
                                        tempDict["description"] = billNameResult["votes"]["vote"]["bill_number"]
                                    else:
                                        tempDict["description"] = billNameResult["votes"]["vote"]["description"]
                                    billNames[keys[voteIndex + newsOffset]] = tempDict
                                    billName = tempDict
                                                       
                        tempOutput = {}                            
                        tempOutput["key"] = keys[voteIndex + newsOffset]
                        tempOutput["time"] = textutil.timeAgo(votes[keys[voteIndex + newsOffset]]["date"], votes[keys[voteIndex + newsOffset]]["time"])
                        tempOutput["name"] = str(jsonOutput["legislators"][votes[keys[voteIndex + newsOffset]]["member_id"]]["friendly_name"])
                        if billName.has_key("link"):
                            tempOutput["link"] = billName["link"]
                            
                        tempOutput["position"] = str(votes[keys[voteIndex + newsOffset]]["position"])
                        if billName.has_key("description"):
                            tempOutput["billname"] = billName["description"]
                        else:
                            tempOutput["billname"] = ""
                        tempOutput["result"] = billName["result"]
                        tempOutput["id"] = str(votes[keys[voteIndex + newsOffset]]["member_id"])
                        jsonOutput["votes"].append(tempOutput)                                                           
                
                jsonOutput["legislators"] = ""
                memcache.set("representedby_billnames", billNames, 86400)

        else:
            jsonOutput["result"] = "error"
            jsonOutput["message"] = "missing IDs"
                
                       
        self.response.out.write(simplejson.dumps(jsonOutput))    
        
        
def main():
    application = webapp.WSGIApplication([('/fb/votes', MainHandler)],
                                       debug=True)
    run_wsgi_app(application)
                                       

if __name__ == '__main__':
    main()
